<?php

if (!defined('__COLA_DIR__')) exit;

/**
 * 登录组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Users_Login extends Widget_Abstract_Users
{
    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        /** 如果已经登录 */
        if ($this->user->hasLogin()) {
			
            /** 设置提示信息 */
            $this->result->set(-1, _t('已经登录'), array('location'=>$this->options->siteUrl));
        }
    }

    /**
     * 初始化函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
        $this->security->protect();

		/** 验证格式 */
        if ($message = $this->form()->validate()) {
			$this->result->set(key($message), current($message));
        }

        /** 开始验证用户 **/
        $valid = $this->user->login($this->request->name, $this->request->password,
            false, 1 == $this->request->remember ? $this->options->time + $this->options->timezone + 30*24*3600 : 0);

        /** 比对密码 */
        if (!$valid) {
			
            /** 防止穷举,休眠3秒 */
            //sleep(3);

            $this->result->set(1, _t('用户名或密码无效'), array('location'=>$this->options->loginUrl));
        }

        /** 跳转验证后地址 */
		$this->result->set(0, _t('成功登录'), array('location'=> $this->options->ucenterUrl));
    }	

    /**
     * 生成表单
     *
     * @access public
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = new Form($this->security->actionUrl('login', false), Form::POST_METHOD);

        /** 用户昵称 */
        $name = new Form_Text('name', NULL, NULL, _t('用户名'));
        $form->addInput($name);

        /** 个人主页地址 */
        $password = new Form_Text('password', NULL, NULL, _t('密码'));
        $form->addInput($password);

        /** 用户动作 */
        $do = new Form_Hidden('do', NULL, 'login');
        $form->set($do);

        /** 提交按钮 */
        $submit = new Form_Submit('submit', NULL, _t('登录'));
        $form->set($submit);

        /** 给表单增加规则 */
        $name->addRule('required', _t('请输入用户名或邮箱.'));
        $password->addRule('required', _t('请输入密码'));

		/** 插件接口 */
		//HOOK PLUG_Login_Form($form, $this);
		
        return $form;
    }

}
